package com.taoz.mianshiwa.service.impl;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taoz.mianshiwa.common.ErrorCode;
import com.taoz.mianshiwa.constant.SortOrder;
import com.taoz.mianshiwa.exception.ThrowUtils;
import com.taoz.mianshiwa.mapper.QuestionMapper;
import com.taoz.mianshiwa.model.dto.question.QuestionEsDTO;
import com.taoz.mianshiwa.model.dto.question.QuestionQueryRequest;
import com.taoz.mianshiwa.model.entity.Question;
import com.taoz.mianshiwa.model.entity.QuestionBankQuestion;
import com.taoz.mianshiwa.model.entity.User;
import com.taoz.mianshiwa.model.vo.QuestionVO;
import com.taoz.mianshiwa.model.vo.UserVO;
import com.taoz.mianshiwa.service.QuestionBankQuestionService;
import com.taoz.mianshiwa.service.QuestionService;
import com.taoz.mianshiwa.service.UserService;
import com.taoz.mianshiwa.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.*;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 题目服务实现
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Resource
    private UserService userService;
    @Resource
    private QuestionBankQuestionService questionBankQuestionService;
    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public Page<Question> searchQuestionByPage(QuestionQueryRequest questionQueryRequest) {
        String searchText = questionQueryRequest.getSearchText();
        int current = questionQueryRequest.getCurrent();
        int pageSize = questionQueryRequest.getPageSize();

        // 筛选条件，未删除的内容中，对标题，内容，答案做分词匹配
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.filter(QueryBuilders.termQuery("isDelete", 0));
        if (StringUtils.isNotBlank(searchText)) {
            boolQueryBuilder.should(QueryBuilders.matchQuery("title", searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("content", searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("answer", searchText));
            boolQueryBuilder.minimumShouldMatch(1);
        }

        // 排序
        SortBuilder<?> sortBuilder = SortBuilders.scoreSort();

        // 分页，ES分页0开始,前端参数和数据库分页参数从1开始
        PageRequest pageRequest = PageRequest.of(current - 1, pageSize);

        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withSorts(sortBuilder)
                .withPageable(pageRequest)
                .build();
        SearchHits<QuestionEsDTO> searchHits = elasticsearchRestTemplate.search(searchQuery, QuestionEsDTO.class);

        Page<Question> page = new Page<>();
        page.setTotal(searchHits.getTotalHits());
        page.setCurrent(current);
        page.setSize(pageSize);

        List<Question> records = new ArrayList<>();
        if (searchHits.hasSearchHits()) {
            List<SearchHit<QuestionEsDTO>> searchHitList = searchHits.getSearchHits();
            records = searchHitList.stream().
                    map(e -> QuestionEsDTO.dtoToObj(e.getContent())).collect(Collectors.toList());
        }
        for (Question record : records) {
            record.setAnswer(null);
        }
        page.setRecords(records);

        return page;
    }

    /**
     * 分页获取题目列表（仅管理员可用）
     *
     * @param questionQueryRequest
     * @return
     */
    public Page<Question> listQuestionByPage(QuestionQueryRequest questionQueryRequest) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();

        QueryWrapper<Question> queryWrapper = getQueryWrapper(questionQueryRequest);

        // 查询某题库下的题目
        Long questionBankId = questionQueryRequest.getQuestionBankId();
        if (questionBankId != null) {
            List<QuestionBankQuestion> list = questionBankQuestionService.lambdaQuery()
                    .select(QuestionBankQuestion::getQuestionId)
                    .eq(QuestionBankQuestion::getQuestionBankId, questionBankId)
                    .list();
            if (CollUtil.isEmpty(list)) {
                return new Page<>();
            }
            List<Long> questionIds = list.stream().map(QuestionBankQuestion::getQuestionId).collect(Collectors.toList());
            queryWrapper.in("id", questionIds);
        }

        // 不查询答案
        queryWrapper.select("id", "title", "content", "tags", "answer", "userId");

        // 查询数据库
        return page(new Page<>(current, size), queryWrapper);
    }

    /**
     * 获取查询条件
     *
     * @param questionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (questionQueryRequest == null) {
            return queryWrapper;
        }

        Long id = questionQueryRequest.getId();
        String title = questionQueryRequest.getTitle();
        String content = questionQueryRequest.getContent();
        String searchText = questionQueryRequest.getSearchText();
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();
        List<String> tagList = questionQueryRequest.getTags();
        Long userId = questionQueryRequest.getUserId();
        String answer = questionQueryRequest.getAnswer();
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText).or().like("answer", answer));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(answer), "answer", answer);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", tag);
            }
        }
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
        queryWrapper.orderBy(true, sortOrder.equals(SortOrder.ASC), sortField);

        return queryWrapper;
    }

    /**
     * 获取题目封装
     *
     * @param question
     * @return
     */
    @Override
    public QuestionVO getQuestionVO(Question question) {
        // 对象转封装类
        return QuestionVO.objToVo(question);
    }

    /**
     * 分页获取题目封装
     *
     * @param questionPage
     * @return
     */
    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage) {
        if (questionPage == null) {
            return null;
        }

        List<Question> questionList = questionPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 对象列表 => 封装对象列表
        List<QuestionVO> questionVOList = questionList.stream().map(question -> {
            QuestionVO questionVO = QuestionVO.objToVo(question);
            questionVO.setTagList(JSONUtil.toList(question.getTags(), String.class));
            return questionVO;
        }).collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);

        return questionVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteQuestions(List<Long> questionIdList) {
        // 删除题目
        lambdaUpdate().in(Question::getId, questionIdList).remove();
        // 同时删除题目对应的关联
        questionBankQuestionService.lambdaUpdate().in(QuestionBankQuestion::getQuestionId, questionIdList).remove();
    }
}
